package com.amkai.aes.webservice.binary.objecthandler.inventory;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.inventory.SimpleItemJob;
import com.amkai.aes.aescommon.service.binary.job.inventory.SimpleItemJobParams;
import com.amkai.aes.aescommon.service.binary.job.inventory.SimpleItemJobResults;
import com.amkai.aes.generatedbeans.dictionary.Item;
import com.amkai.aes.generatedbeans.inventory.ResourceType;
import com.amkai.aes.generatedbeans.organization.Department;
import com.amkai.aes.server.dictionary.DictionarySchedulingResourceManager;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.rad.designerbase.beans.RADBean;

public class SimpleItemHandler implements JobObjectHandler<SimpleItemJob, SimpleItemJobParams, SimpleItemJobResults>{
	private static final Log logger = LogFactory.getLog(SimpleItemHandler.class);

	
	
	
	@Override
	public SimpleItemJobResults process(SimpleItemJob job,
			SimpleItemJobParams params) throws Exception {
		
		SimpleItemJobResults results = new SimpleItemJobResults();

		SessionManager sm = null;
		try {
			sm = SiteManager.Start();
			sm.openSession();
			sm.openTransaction();
			
			SimpleItemQueryBuilder builder = new SimpleItemQueryBuilder(params, job.getModuleDepartment(), new ResolverServiceManager(sm, job));

			if (params.getId() == null) {
				String hqlQuery = builder.getAllItemQuery();
				logger.debug(hqlQuery);
				Query query = sm.execute(hqlQuery);
				for (int i=0; i<builder.getQueryParameterCount(); i++) {
					query.setParameter(i, builder.getQueryParameterAt(i));
				}
				List<?> items = query.list();
				for (Object res : items) {
					if (!(res instanceof Object[])) continue;
					Object[] arr = (Object[])res;


					int index = 0;
					for (Iterator<PropertyHQLGenerator> it=builder.getFieldGenerators().iterator(); it.hasNext();index++) {
						arr[index] = it.next().resolveValue(arr[index]);
					}
				}
				results.setItems(items);
			} else if (params.getClass() != null) {
				String hqlQuery = builder.getSingleItemQuery();
				logger.debug(hqlQuery);
				Query query = sm.execute(hqlQuery);
				for (int i=0; i<builder.getQueryParameterCount(); i++) {
					query.setParameter(i, builder.getQueryParameterAt(i));
				}
				// KKORNEL: AES-14980 - RADBean --> Item
				Item item = (Item)query.uniqueResult();
				resolveTransientProperties(item, sm, job.getModuleDepartment());
				results.setSingleItem(item);
			}
			sm.commitTransaction();
		} catch (Exception e) {
			if (sm != null){
				sm.rollbackTransaction();
			}
			logger.error("SimpleItemHandler: ", e);
			throw e;
		} finally {
			if (sm != null) sm.closeSession();
		}
		return results;
	}
	
	ResourceType findResourceType(int val) {
		for (ResourceType type : ResourceType.class.getEnumConstants()) {
			if (type.ordinal() == val) return type;
		}
		return null;
	}
	
	private void resolveTransientProperties(RADBean bean, SessionManager sm, Department department) throws Exception {
		if (bean instanceof Item) {
			try {
				// KKORNEL: AES-4465
				//DictionaryManager dm = new DictionaryManager(sm);
				((Item)bean).setTranzientActive(/*dm.isActive((Item)bean, department)*/((Item)bean).isActive());
			} catch (Exception e) {
				logger.error("SimpleItemHandler: ", e);
			}
			DictionarySchedulingResourceManager dsrm = new DictionarySchedulingResourceManager(sm);
			bean.setTransientSchedulingResource(dsrm.isActiveSchedulingResource((Item)bean));
		}
	}

}
